package com.hzlx.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.hzlx.*;
import com.hzlx.feign.baseDataService;
import com.hzlx.feign.materialService;
import com.ruoyi.common.core.utils.DateUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Pair;
import org.springframework.stereotype.Service;
import com.hzlx.mapper.MesWorkOrdersMapper;
import com.hzlx.domain.MesWorkOrders;
import com.hzlx.service.IMesWorkOrdersService;

/**
 * 工单管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-30
 */
@Service
public class MesWorkOrdersServiceImpl implements IMesWorkOrdersService

{
    @Resource
    materialService materialService;
    @Resource
    baseDataService  basedataService;
    @Autowired
    private MesWorkOrdersMapper mesWorkOrdersMapper;

    /**
     * 查询工单管理
     * 
     * @param id 工单管理主键
     * @return 工单管理
     */
    @Override
    public MesWorkOrders selectMesWorkOrdersById(Long id)
    {
        return mesWorkOrdersMapper.selectMesWorkOrdersById(id);
    }

    /**
     * 查询工单管理列表
     * 
     * @param mesWorkOrders 工单管理
     * @return 工单管理
     */
    @Override
    public List<MesWorkOrders> selectMesWorkOrdersList(MesWorkOrders mesWorkOrders)
    {
        return mesWorkOrdersMapper.selectMesWorkOrdersList(mesWorkOrders);
    }

    /**
     * 新增工单管理
     * 
     * @param mesWorkOrders 工单管理
     * @return 结果
     */
    @Override
    public ResultDto<String> insertMesWorkOrders(MesWorkOrders mesWorkOrders)
    {
        //1、获取productId
        //2、查询bom表中productId对应的bomId
        BomsDto bomsDto=new BomsDto();
        bomsDto.setProductId(mesWorkOrders.getProductId());
        List<BomsDto> bomsDtos= basedataService.list(bomsDto);
        System.out.println("查询到的bom-------------"+bomsDtos);
         //3、根据bomId 查询mes_bom_components 获取所有的component_material_id 和需要消耗量quantity
        List<Long> insufficientMaterials = new ArrayList<>();//记录不够的材料
        bomsDtos.stream()
                .map(bom -> {
                    BomComponentsDto bomComponentsDto=new BomComponentsDto();
                    bomComponentsDto.setBomId(bom.getBomId());
                    // 3. 根据bomId查询mes_bom_components表
                    List<BomComponentsDto> componentsDtos =basedataService.BomComponentsList(bomComponentsDto);
                    System.out.println("查到的長度------"+componentsDtos.size());
                    return Pair.of(bom, componentsDtos); // 使用Pair存储BOM和对应的组件列表
                }).forEach(pair -> {
                  List<BomComponentsDto> componentsDtosP=pair.getSecond();
                  for (BomComponentsDto componentsDto:componentsDtosP){
                      MesMaterialBatchesDto mesMaterialBatchesDto= materialService.getInfoDto(componentsDto.getComponentMaterialId());
                      BigDecimal requiredQty = componentsDto.getQuantity().multiply(new BigDecimal(mesWorkOrders.getPlannedQuantity()));
                      if (requiredQty.compareTo(mesMaterialBatchesDto.getCurrentQuantity()) > 0) {

                          insufficientMaterials.add(mesMaterialBatchesDto.getMaterialId());

                          // 当 requiredQty 大于 mesMaterialBatchesDto.getCurrentQuantity() 时的业务逻辑
                      }
                  }
                  System.out.println("库存检验完成---------");
                    System.out.println(pair.getFirst()+"----"+pair.getSecond());
                });
         //4、每一个material_id进行对比，若是够plan_quantity等于plan_quantity减去quantity
         if (insufficientMaterials.size()>0){
             System.out.println("库存不足--------------");
             // 将 Long 类型的物料 ID 拼接成字符串，格式如 "物料 1、2、3 储存不足"
             String message = insufficientMaterials.stream()
                     // 将每个 Long 类型的 ID 转换为字符串
                     .map(String::valueOf)
                     // 拼接成以“、”分隔的字符串，如 "1、2、3"
                     .collect(Collectors.joining("、"));
             // 构造提示信息，拼接成完整的提示文案
             message = "物料 " + message + " 储存不足";
             return ResultDto.<String>builder()
                     .code(4081)
                     // 设置拼接好的提示信息
                     .msg(message)
                     .build();
         }else{
             System.out.println("库存足够-----");
             bomsDtos.stream()
                     .map(bom -> {
                         BomComponentsDto bomComponentsDto=new BomComponentsDto();
                         bomComponentsDto.setBomId(bom.getBomId());
                         // 3. 根据bomId查询mes_bom_components表
                         List<BomComponentsDto> componentsDtos =basedataService.BomComponentsList(bomComponentsDto);
                         return Pair.of(bom, componentsDtos); // 使用Pair存储BOM和对应的组件列表
                     }).forEach(pair -> {
                         List<BomComponentsDto> componentsDtosP=pair.getSecond();
                         for (BomComponentsDto componentsDto:componentsDtosP){
                             MesMaterialBatchesDto mesMaterialBatchesDto= materialService.getInfoDto(componentsDto.getComponentMaterialId());
                             BigDecimal requiredQty = componentsDto.getQuantity().multiply(new BigDecimal(mesWorkOrders.getPlannedQuantity()));
                             //进行删减
                          mesMaterialBatchesDto.setPlanQuantity( mesMaterialBatchesDto.getPlanQuantity().subtract(requiredQty));
                             materialService.editByWorkOrder(mesMaterialBatchesDto);
                             System.out.println("库存"+mesMaterialBatchesDto.getMaterialId()+"删减成功-------");
                         }

                     }
                     );
             mesWorkOrdersMapper.insertMesWorkOrders(mesWorkOrders);
             return ResultDto.<String>builder().msg("创建订单成功").code(200).build();

         }
//        return mesWorkOrdersMapper.insertMesWorkOrders(mesWorkOrders);
    }
    // 将Map转换为BomsDto
    private BomsDto convertToBomsDto(Map<String, Object> map) {
        BomsDto dto = new BomsDto();
        dto.setBomId((Long) map.get("bomId"));
        dto.setProductId((Long) map.get("productId"));
        // 设置其他属性
        return dto;
    }

    // 将Map转换为BomComponentsDto
    private BomComponentsDto convertToBomComponentsDto(Map<String, Object> map) {
        BomComponentsDto dto = new BomComponentsDto();
        dto.setBomId((Long) map.get("bomId"));
        dto.setComponentMaterialId((Integer) map.get("componentMaterialId"));
        dto.setQuantity((BigDecimal) map.get("quantity"));
        // 设置其他属性
        return dto;
    }
    /**
     * 修改工单管理
     * 
     * @param mesWorkOrders 工单管理
     * @return 结果
     */
    @Override
    public int updateMesWorkOrders(MesWorkOrders mesWorkOrders)
    {
        mesWorkOrders.setUpdateTime(DateUtils.getNowDate());
        return mesWorkOrdersMapper.updateMesWorkOrders(mesWorkOrders);
    }

    /**
     * 批量删除工单管理
     * 
     * @param ids 需要删除的工单管理主键
     * @return 结果
     */
    @Override
    public int deleteMesWorkOrdersByIds(Long[] ids)
    {
        return mesWorkOrdersMapper.deleteMesWorkOrdersByIds(ids);
    }

    /**
     * 删除工单管理信息
     * 
     * @param id 工单管理主键
     * @return 结果
     */
    @Override
    public int deleteMesWorkOrdersById(Long id)
    {
        return mesWorkOrdersMapper.deleteMesWorkOrdersById(id);
    }

    @Override
    public void updateMesWorkOrdersByMaterial(WorkOrderDto workOrderDto) {
        MesWorkOrders mesWorkOrders = new MesWorkOrders();
        BeanUtils.copyProperties(workOrderDto, mesWorkOrders);
        mesWorkOrdersMapper.updateMesWorkOrders(mesWorkOrders);
    }

    @Override
    public List<WorkOrderDto> selectMesWorkOrdersByProductId(Long productId) {
        return mesWorkOrdersMapper.selectListByProductId(productId);
    }
}
